<?php
/**
 * Created by xiaoZeng.
 * QQ: 1031045720 Wechat:zjwx6064
 * Date: 2018/9/16
 * Time: 22:45
 */
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Cache;
use think\Db;
class WxLogin extends Controller{

    public $is_sense = 0;//是否参与游戏标记  0未参与，1参与
    public $uid = '';//用户ID

    /**
     * 基础控制器初始化
     * @author 苏晓信
     */
    public function _initialize()
    {

        $rdata = [
            'code' => 0,
            'msg'  => ''
        ];
        $get_data = input('get.') ? input('get.') : input('post.');
        if(empty($get_data['scoreId'])){
            $rdata['msg'] = '牌局ID为空';
            echo json_encode($rdata,JSON_UNESCAPED_UNICODE);exit;
        }

        //判断是否微信浏览器打开
        $isWx = $this->is_wxBrowers();
        if(!$isWx){
            //参与标记
            $this->is_sense = 0;
            $this->uid = 0;
            Session::init([
                'expire'         => 3600
            ]);
            Session::set('userId',0);
            return;
        }


        //Session::delete('userId');
        //是否已登陆
        $userId = Session::get('userId');
        if($userId){
            //是否当局参与者
            $r = Db::table('record_tabletotalscore')->where(['Uid'=>$userId,'ScoreID'=>$get_data['scoreId']])->find();
            if($r){
                //参与标记
                $this->is_sense = 1;
                $this->uid = $userId;
                Session::init([
                    'expire'         => 3600
                ]);
                Session::set('userId',$userId);
            }else{
                //是否是群主
                $qzInfo = Db::table('record_tabletotalscore')->where(['ScoreID'=>$get_data['scoreId']])->find();
                if($qzInfo['GroupID']){
                    $qzRes = Db::table('club_manager')->where(['ClubID'=>$qzInfo['GroupID'],'CreateID'=>$userId])->field('CreateID')->find();
                    if($qzRes){
                        //参与标记
                        $this->is_sense = 1;
                        $this->uid = $userId;
                        Session::init([
                            'expire'         => 3600
                        ]);
                        Session::set('userId',$userId);
                    }else{
                        //未参与标记
                        $this->is_sense = 0;
                    }

                }else{
                    //未参与标记
                    $this->is_sense = 0;
                }
            }
            return;
        }


        //获取微信登录授权
        $wxUserInfo = $this->wxLogin();
        if($wxUserInfo){
            //搜索UID
            $user = Db::table('account_info')->where('Account',$wxUserInfo->unionid)->field('Account,uid')->find();
            if($user){
                //是否当局参与者
                $r = Db::table('record_tabletotalscore')->where(['Uid'=>$user['uid'],'ScoreID'=>$get_data['scoreId']])->find();
                if($r){
                    //参与标记
                    $this->is_sense = 1;
                    $this->uid = $user['uid'];
                    Session::init([
                        'expire'         => 3600
                    ]);
                    Session::set('userId',$user['uid']);
                }else{
                    //是否是群主
                    $qzInfo = Db::table('record_tabletotalscore')->where(['ScoreID'=>$get_data['scoreId']])->find();
                    if($qzInfo['GroupID']){
                        $qzRes = Db::table('club_manager')->where(['ClubID'=>$qzInfo['GroupID'],'CreateID'=>$user['uid']])->field('CreateID')->find();
                        if($qzRes){
                            //参与标记
                            $this->is_sense = 1;
                            $this->uid = $user['uid'];
                            Session::init([
                                'expire'         => 3600
                            ]);
                            Session::set('userId',$user['uid']);
                        }else{
                            //未参与标记
                            $this->is_sense = 0;
                        }

                    }else{
                        //未参与标记
                        $this->is_sense = 0;
                    }
                }

            }else{
                $rdata['msg'] = '您尚未注册游戏账号';
                echo json_encode($rdata,JSON_UNESCAPED_UNICODE);exit;
            }
        }else{
            $rdata['msg'] = '微信授权登录错误：'.$wxUserInfo;
            echo json_encode($rdata,JSON_UNESCAPED_UNICODE);exit;
        }


    }

    //微信登陆
    public function wxLogin(){
        $code = input('code');
        $cacheCode = Cache::get('code');
        if($code){
            //限制微信重定向两次BUG
            if ($cacheCode == $code) {
                exit;
            }

            Cache::set('code', $code, 3600);

            //已获取code码，获取openid
            $openidData = $this->getOpenidFromMp($code);

            //获取用户详情
            $wxUserInfo = $this->getWxUserInfo($openidData);
            return $wxUserInfo;

        }else{
            //触发微信返回code码
            $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
            $url = $this->__CreateOauthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        }
    }

    //获取微信用户详情
    public function getWxUserInfo($openidData){
        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$openidData['access_token'].'&openid='.$openidData['openid'].'&lang=zh_CN';
        return json_decode(file_get_contents($user_info_url));
    }


    /**
     *
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     *
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = config('wxconfig')['appID'];
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_userinfo";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }

    /**
     *
     * 拼接签名字符串
     * @param array $urlObj
     *
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     *
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     *
     * @return openid
     */
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        //初始化curl
        $ch = curl_init();
        //设置超时
        // curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //运行curl，结果以jason形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        //取出openid
        $data = json_decode($res,true);
        // 结果检测
        if(empty($data['openid'])) {
            dump($data);exit;
        }
        return $data;
    }


    /**
     *
     * 构造获取open和access_toke的url地址
     * @param string $code，微信跳转带回的code
     *
     * @return 请求的url
     */
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = config('wxconfig')['appID'];
        $urlObj["secret"] = config('wxconfig')['appsecret'];
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }

    /**
     * 是否是微信浏览器
     * @return bool
     */
    function is_wxBrowers(){
        $str=strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger');
        if($str!==false){
            return true; //微信浏览器
        }
        return false; //非微信浏览器
    }
}